package BandB.Tool.GPhoneManager.TaskManager.config;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.util.Log;

public class XmlManager {

//	private Document mDocument;
	private Context mContext;
	private static final String CONFIG_FILE_NAME = "scheduler_config.xml";
	private static final String COMMENT = "config for service scheduled to kill processes";
	private static final String ELEMENT_ROOT = "config";
	public static final String ELEMENT_TYPE = "type";
	public static final String ELEMENT_VALUE = "value";
	private static final String ELEMENT_LAST_MODIFIED = "last_modified";

	public static final String SPLIT = "_";
	public static final String TYPE_TIME_SPAN = "timespan";
	public static final String TYPE_EVERYDAY_TIME = "everday";
	private static final String TAG = "XmlManager";

	public XmlManager(Context c) throws IOException, DocumentException {
		mContext = c;

		File file = mContext.getFileStreamPath(CONFIG_FILE_NAME);
		if (file.exists()) {
			Log.e(TAG, "file exist, load document");
//			mDocument = new SAXReader().read(file);
		} else {
			Log.e(TAG, "file not exist, create file...");
			generateConfigFile();
		}
	}

	private void generateConfigFile() throws DocumentException, IOException {

		FileOutputStream outPutStream = mContext.openFileOutput(
				CONFIG_FILE_NAME, Context.MODE_WORLD_WRITEABLE);
		outPutStream.close();
		Document mDocument = DocumentHelper.createDocument();
		
		Element rootElement = mDocument.addElement(ELEMENT_ROOT);
		rootElement.addComment(COMMENT);
		rootElement.addProcessingInstruction("target", "text");
		Element typeElement = rootElement.addElement(ELEMENT_TYPE);
		typeElement.setText(TYPE_TIME_SPAN);
		// journalElement.addAttribute("title", "XML Zone");
		// journalElement.addAttribute("publisher", "IBM developerWorks");

		Element valueElement = rootElement.addElement(ELEMENT_VALUE);
		valueElement.setText("24_00");
		// articleElement.addAttribute("level", "Intermediate");
		// articleElement.addAttribute("date", "December-2001");
		Element lastModifiedElement = rootElement
				.addElement(ELEMENT_LAST_MODIFIED);
		// titleElement.setText("Java configuration with XML Schema");
		Date date = new Date();
		lastModifiedElement.setText(date.toLocaleString());
		OutputFormat format = OutputFormat.createPrettyPrint();
		try {
			XMLWriter output = new XMLWriter(new FileWriter(new File(mContext
					.getFilesDir()
					+ "/" + CONFIG_FILE_NAME)), format);
			output.write(mDocument);
			output.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		
	}

	@SuppressWarnings("unchecked")
	public boolean writeConfig(String type, String value)
			throws FileNotFoundException, XmlPullParserException,
			DocumentException {
		Document mDocument = new SAXReader().read(new File(mContext.getFilesDir() + "/"
				+ CONFIG_FILE_NAME));
		Element rootElement = mDocument.getRootElement();
		List<Element> nodes = rootElement.elements();
		List<String> valueList = new ArrayList<String>();
		valueList.add(type);
		valueList.add(value);
		Date date = new Date();
		valueList.add(date.toLocaleString());
		nodes.get(0).setText(valueList.get(0));
		nodes.get(1).setText(valueList.get(1));
		nodes.get(2).setText(valueList.get(2));

		OutputFormat format = OutputFormat.createPrettyPrint();
		try {
			XMLWriter output = new XMLWriter(new FileWriter(new File(mContext
					.getFilesDir()
					+ "/" + CONFIG_FILE_NAME)), format);
			output.write(mDocument);
			output.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		return true;
	}

	public HashMap<String, String> readConfig() {

		Document mDocument;
		HashMap<String, String> configHashMap = new HashMap<String, String>();
		
		try {
			mDocument = new SAXReader().read(new File(mContext.getFilesDir() + "/"
					+ CONFIG_FILE_NAME));
		} catch (DocumentException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return configHashMap;
		}
		
		Element rootElement = mDocument.getRootElement();
		List<String> listString = new ArrayList<String>();
		List<?> nodes = rootElement.elements();
		for (Iterator<?> iterator = nodes.iterator(); iterator.hasNext();) {
			// Object object = (Object) iterator.next();
			Element element = (Element) iterator.next();
			String value = element.getText();
			listString.add(value);
		}
		configHashMap.put(ELEMENT_TYPE, listString.get(0));
		configHashMap.put(ELEMENT_VALUE, listString.get(1));
		configHashMap.put(ELEMENT_LAST_MODIFIED, listString.get(2));

		return configHashMap;
	}

}
